<?php


namespace App\Utils;


use App\Model\Device;
use App\Model\DeviceCallCountsDaily;
use App\Model\Normal;
use App\Model\User;
use App\Model\UserCallCountsDaily;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Hyperf\DbConnection\Db;
class Helper
{

    /**
     * 拼接班级名称
     * @param $gradeName
     * @param $classes
     * @return string
     */
    public static function getClassesName($gradeName, $classes): string
    {
        return $gradeName . "({$classes})班";
    }

    /**
     * 格式化成 01,02这样的编号
     * @param $no
     * @return mixed|string
     */
    public static function formatNo($no)
    {
        if ($no < 10) {
            return '0' . $no;
        }
        return $no;
    }

    /**
     * 统一设备mac地址
     * @param $mac
     * @return string
     */
    public static function formatMac($mac): string
    {
        return strtolower(str_replace(":", "", $mac));
    }

    /**
     * 获取 Redis 实例（静态方法专用）
     */
    private static function getRedis(): Redis
    {
        // 通过容器直接获取 Redis 实例
        return ApplicationContext::getContainer()->get(Redis::class);
    }
    public static function usedAdd($userId,$mac){
        $redis = self::getRedis();
        $recordMonth = $redis->get('user_call_counts_month_key_'. $userId);
        $monthNow = date('Y-m'.$userId);
        if($recordMonth!=$monthNow){
            $redis->set('user_call_counts_month_key_'. $userId, $monthNow);
            //增加设备表的总使用次数和月使用次数
            Device::where('mac', $mac)->update([
                'call_count' => DB::raw('call_count + 1'),
                'call_count_month' => 1
            ]);
            //增加用户的调用次数
            User::where('id', $userId)->update([
                'call_count_used' => DB::raw('call_count_used + 1'),
                'call_count_used_month' => 1
            ]);
       //     Normal::logger($recordMonth.'---11111111---'.$userId.'----'.$monthNow,'order-queue');
        }else{
            //增加设备表的总使用次数和月使用次数
     //       Normal::logger('222222','order-queue');
            Device::where('mac', $mac)->update([
                'call_count' => DB::raw('call_count + 1'),
                'call_count_month' => DB::raw('call_count_month + 1')
            ]);
            User::where('id', $userId)->update([
                'call_count_used' => DB::raw('call_count_used + 1'),
                'call_count_used_month' => DB::raw('call_count_used_month + 1')
            ]);
        }

        UserCallCountsDaily::addUseCount($userId);
        DeviceCallCountsDaily::addUseCount($mac);
        return true;
    }
}
